package com.baidu.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baidu.entity.UserInfo;
import com.baidu.mapper.UserInfoMapper;
import com.baidu.response.Response;
import com.baidu.service.UserInfoService;
import com.baidu.utils.CacheUtil;
import com.baidu.utils.JwtUtil;
import com.baidu.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baidu.entity.UserInfo;

import java.util.Collections;
import java.util.List;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public List<UserInfo> selectAll() {
        return userInfoMapper.selectAll();
    }

    public Response<String> login(UserInfoVo userInfoVo) {
        //用户输入的验证码
        String userInputCode = userInfoVo.getVerificationCode();
        //从缓存中获取的验证码,这里前期是写的固定的IP地址，
        // 是为了方便测试，实际生产环境中应该是根据用户的IP地址获取缓存中的验证码
        String cacheCode = CacheUtil.captchaMap.get("172.0.0.1");
        //比较两者是否一致
        if (!cacheCode.equalsIgnoreCase(userInputCode)) {
            return Response.fail(501, "验证码错误");
        }

        //判断账号是否存在
        UserInfo userInfo = userInfoMapper.findByCode(userInfoVo.getUserCode());
        if (userInfo == null) {
            return Response.fail(501, "账号不存在");
        }
        //该账号在数据库的密码
        String userPwd = userInfo.getUserPwd();

        //用户输入的密码
        String userInputPwd = SecureUtil.md5(userInfoVo.getUserPwd());
        if (!userPwd.equals(userInputPwd)) {
            return Response.fail(501, "账号或密码错误");
        }
        //颁发令牌
        String token = JwtUtil.generateToken(userInfo.getUserId(), userInfo.getUserName(), userInfo.getUserCode());
        return Response.success(200, "登录成功", token);

    }
}

